/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gray.swing.button;

import gray.Frame;
import util.observer.Trigger;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;

/**
 *
 * @author martin
 */
public class Button extends JButton implements Frame<Container> ,ActionListener{
    private final Trigger _observer;
    private final Object _obj;
    private final Frame<Container> _valid;
    
    private Button(final Trigger observer, final String name, final Character key, final Object obj, final Frame<Container> valid){
      super(name);
      if(observer!=null)
        addActionListener(this);
      _observer = observer;
      _obj = obj;
      _valid = valid;
      if (key != null)
        setMnemonic(key);

    }
    
    public static Frame<Container> factory(final Trigger observer, final String name, final Character key){
        return new Button(observer, name, key, null, null);
    }
    
    public static Frame<Container> factoryWithMsg(final Trigger observer, final String name, final Character key, final Object msg){
        return new Button(observer, name, key, msg, null);
    }
    
    public static Frame<Container> factoryValid(final Trigger observer, final String name, final Character key, final Frame<Container> valid){
        return new Button(observer, name, key, null, valid);
    }
    
    public static Frame<Container> factoryValidWithMsg(final Trigger observer, final String name, final Character key, final Object msg, final Frame<Container> valid){
        return new Button(observer, name, key, msg, valid);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        if (_valid==null)
            _observer.poke(_obj);
        else if (_valid.ready())
            _observer.poke(_obj);
        else
            JOptionPane.showMessageDialog(null, 
                                          "un ou plusieurs des champs dépendant est incomplet",
                                          "vraiment pas",
                                          JOptionPane.ERROR_MESSAGE);
    }   

    @Override
    public Container container() {
        return this;
    }

    @Override
    public Boolean ready() {
        return true;
    }
    
}
